package com.hdax.dm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hdax.dm.beans.user.User;
import com.hdax.dm.constant.ErrConstant;
import com.hdax.dm.dto.loginDto;
import com.hdax.dm.exceptions.DmException;
import com.hdax.dm.mappers.loginMapper;
import com.hdax.dm.mapstucts.loginDtoMapper;
import com.hdax.dm.service.loginService;
import com.hdax.dm.utils.request.tokenutil;
import com.hdax.dm.utils.response.CommonResponse;
import com.hdax.dm.utils.response.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
public class loginServiceImpl extends ServiceImpl<loginMapper, User> implements loginService {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private loginDtoMapper loginDtoMapper;

    //获取验证码
    @Override
    public CommonResponse<String> msg(Map<String, String> params) {
        String phone = params.get("phone");

        //防止用户频繁请求验证码
        String key = "vcode:"+phone;
        if (redisTemplate.opsForValue().get(key)!=null){
            throw new DmException(ErrConstant.ErrCodeConstant.REPEAT_CODE_VCODE,ErrConstant.ErrMsgConstant.REPEAT_MSG_VCODE);
        }

        if (phone == null || phone.trim().length()!=11){
            throw new DmException(ErrConstant.ErrCodeConstant.ERR_CODE_PHONE_NUMBER,ErrConstant.ErrMsgConstant.ERR_MSG_PHONE_NUMBER);
        }
        //生成验证码
        Random random = new Random();
        int min = 1000;
        int max = 10000;
        int rand = random.nextInt(max);
        while(rand<min){
            rand = random.nextInt(max);
        }

        //将生成的验证码存储到redis中
        redisTemplate.opsForValue().set("vcode:"+phone,rand+"",60L, TimeUnit.SECONDS);

        //发送验证码到消息队列
        Map<String,String> map = new HashMap<>();
        map.put("phone",phone);
        map.put("vcode",rand+"");
//        rabbitTemplate.convertAndSend("dmsms",map);
        return ResponseUtil.returnSuccess(rand+"");
    }

    //验证码登录
    @Override
    public CommonResponse<loginDto> msglogin(Map<String, String> params) {

        String phone = params.get("phone");
        String vcode = params.get("vcode");

        //根据指定的key从redis中读取数据
        String key = "vcode:"+phone;
        String realCvode = redisTemplate.opsForValue().get(key);

        //如果realCvode他是空的，则说明验证码不存在
        if (realCvode == null) {
            throw new DmException(ErrConstant.ErrCodeConstant.NOT_EXISTS_CODE_VCODE,ErrConstant.ErrMsgConstant.NOT_EXISTS_MSG_VCODE);
        }
        //获取验证码不为空，但是输入的和获取的不相等，则说明验证码输入错误
        if (!realCvode.equals(vcode)){
            throw new DmException(ErrConstant.ErrCodeConstant.WRONG_CODE_VCODE,ErrConstant.ErrMsgConstant.WRONG_MSG_VCODE);
        }
        //登陆成功
        //根据输入的手机号查询用户信息
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("phone",phone);
        User user = baseMapper.selectOne(queryWrapper);

        if (user==null){
            User user1= new User();
            user1.setPhone(phone);
            user1.setNickName(phone);
            user1.setRealName(phone);
            baseMapper.insert(user1);

            QueryWrapper queryWrapper1 = new QueryWrapper();
            queryWrapper1.eq("phone",phone);
            user = baseMapper.selectOne(queryWrapper1);
        }

        //使用JWT生成token
        String token = tokenutil.createdToken(user.getId(), user.getNickName());

        //把token存放到redis中
        redisTemplate.opsForValue().set("token:"+user.getId(),token,180,TimeUnit.MINUTES);
        loginDto dto = loginDtoMapper.toTarget(user);
        dto.setToken(token);
        dto.setGenTime(tokenutil.createdate.getTime()+"");
        dto.setExtTime(tokenutil.expreDate.getTime()+"");

        return ResponseUtil.returnSuccess(dto);
    }

    //手机号密码登录
    @Override
    public CommonResponse<loginDto> userlogin(Map<String, String> params) {

        String phone = params.get("phone");
        String password = params.get("password");

        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("phone",phone);
        queryWrapper.eq("password",password);
        User user = baseMapper.selectOne(queryWrapper);

        //如果user他是空的，则说明用户名或密码错误
        if (user == null) {
            throw new DmException(ErrConstant.ErrCodeConstant.WRONG_CODE_USER,ErrConstant.ErrMsgConstant.WRONG_MSG_USER);
        }

        loginDto dto = loginDtoMapper.toTarget(user);
        dto.setToken("token");
        dto.setGenTime("120");
        dto.setExtTime("60");

        return ResponseUtil.returnSuccess(dto);
    }
}
